import axios from 'axios';

const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'development' 
    ? 'http://localhost:5001'  // 移除 /api，因为我们会在请求时添加
    : '',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true // 允许跨域请求携带凭证
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 确保所有请求都以 /api 开头
    if (!config.url.startsWith('/api/')) {
      config.url = `/api${config.url}`;
    }
    
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => response,
  (error) => {
    console.log('请求错误:', error);
    console.log('响应状态:', error.response?.status);
    console.log('响应数据:', error.response?.data);
    return Promise.reject(error);
  }
);

export default instance; 